package com.example.plugin;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.util.Properties;

@Intercepts({@Signature(type=StatementHandler.class,method = "prepare",args = {Connection.class})})
public class MyPlugin implements Interceptor{
    private int limit;
    private String dbType;


    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        System.out.println("this is my plugin");
        System.out.println(limit);
        System.out.println(dbType);

        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        MetaObject metaStmtHandler = SystemMetaObject.forObject(statementHandler);

        while (metaStmtHandler.hasGetter("h")){
            Object object = metaStmtHandler.getValue("h");
            metaStmtHandler = SystemMetaObject.forObject(object);
        }

        while (metaStmtHandler.hasGetter("target")){
            Object object = metaStmtHandler.getValue("target");
            metaStmtHandler = SystemMetaObject.forObject(object);
        }

        String sql = (String)metaStmtHandler.getValue("delegate.boundSql.sql");
        System.out.println("my plugin sql:" + sql);

        while (metaStmtHandler.hasGetter("parameterMappings")){
            Object object = metaStmtHandler.getValue("target");
            metaStmtHandler = SystemMetaObject.forObject(object);
        }

        //metaStmtHandler.getValue("");

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        System.out.println("regist : " + target.getClass());
        return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {
        String strLimit = properties.getProperty("limit");
        this.limit = Integer.parseInt(strLimit);
        this.dbType = properties.getProperty("dbType");
    }
}
